package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.domain.Message;
import com.liuzhilin.service.ManagerService;
import com.liuzhilin.service.MessageService;
import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.stream.Collectors;

@WebServlet("/emailUpdateType")
public class EmailUpdateType extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型为 JSON
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        // 获取请求体中的数据
        String requestBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(requestBody);

        // 提取用户名和邮件内容
        String username = jsonNode.get("username").asText();
        String message = jsonNode.get("message").asText();

        boolean Success = MessageService.updateMessageType(username,message);

        // 返回响应
        if (Success) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新邮件类型失败");
        }
    }

    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
